<template>
  <div class="app-container">
    <div class="filterDiv">
      <label class="label" style="padding-left:0">类别:</label>
      <el-select v-model="listQuery.queryParam.periodType" placeholder="类别" size="small" @change="typeChange">
        <el-option label="月报" value="1" />
        <el-option label="季报" value="3" />
        <el-option label="上半年报" value="6" />
        <el-option label="年报" value="C" />
      </el-select>
      <label v-if="listQuery.queryParam.periodType && listQuery.queryParam.periodType !== '1'" class="label">年份:</label>
      <el-select v-if="listQuery.queryParam.periodType && listQuery.queryParam.periodType !== '1'" v-model="listQuery.queryParam.periodYear" placeholder="年份" size="small" @change="getData">
        <el-option v-for="item in yearArr" :key="item" :label="item + '年'" :value="item" />
      </el-select>
      <label v-if="listQuery.queryParam.periodType==3" class="label">季度:</label>
      <el-select v-if="listQuery.queryParam.periodType==3" v-model="listQuery.queryParam.quarter" placeholder="季度" size="small" @change="getData">
        <el-option label="一季度" value="1" />
        <el-option label="二季度" value="2" />
        <el-option label="三季度" value="3" />
        <el-option label="四季度" value="4" />
      </el-select>
      <label v-if="listQuery.queryParam.periodType==1" class="label">期间:</label>
      <el-select v-if="listQuery.queryParam.periodType==1" v-model="listQuery.queryParam.periodCode" placeholder="会计期间" size="small" @change="getData">
        <el-option v-for="item in periodList" :key="item.id" :label="item.text" :value="item.id" />
      </el-select>
    </div>
    <div class="contentDiv">
      <el-table :data="tableData" border fit highlight-current-row cell-class-name="tpCell" style="width: 100%;" size="small">
        <el-empty slot="empty" :image-size="120" />
        <el-table-column label="日期" align="center" width="140">
          <template slot-scope="{row}">
            <span>{{ row.jeDate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="凭证字号" align="center" prop="jeSeq" width="150">
          <template slot-scope="{row}">
            <span class="tlink" @click="handleCompile(row.id)">{{ row.jeCatogeryName }} - {{ row.jeSeq | jeSeqFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column label="摘要" min-width="120">
          <template slot-scope="{row}">
            <p v-for="(item,index) in row.lineList" :key="index" clss="pCell">{{ item.summary }}</p>
          </template>
        </el-table-column>
        <el-table-column label="科目名称" min-width="160">
          <template slot-scope="{row}">
            <p v-for="(item,index) in row.lineList" :key="index" clss="pCell" style="width:max-content;min-width:100%">
              <span>{{ item.longName }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="借方金额" width="100">
          <template slot-scope="{row}">
            <p v-for="(item,index) in row.lineList" :key="index" clss="pCell">
              <span v-if="item.accountedDr" class="tx-r" style="padding-right:0">{{ item.accountedDr }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="贷方金额" width="100">
          <template slot-scope="{row}">
            <p v-for="(item,index) in row.lineList" :key="index" clss="pCell">
              <span v-if="item.accountedCr" class="tx-r" style="padding-right:0">{{ item.accountedCr }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="现金流向" min-width="140">
          <template slot-scope="{row}">
            <p v-for="(item,index) in row.lineList" :key="index" clss="pCell" style="width:max-content;width:100%;padding:0">
              <el-select v-model="item.cashFlowId" :disabled="!!item.cashFlowFlag" placeholder="现金流向" size="small" style="width:100%;">
                <el-option v-for="ele in cashFlowList" :key="ele.id" :label="ele.text" :value="ele.id" />
              </el-select>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="流向借方" align="right">
          <template slot-scope="scope">
            <p v-for="(item,index) in scope.row.lineList" :key="index" clss="pCell" style="height:32px;padding:0;">
              <input v-model="item.cashFlowDr" class="tx-r" :disabled="!!item.cashFlowFlag" style="padding-right:10px" oninput="value=value.replace(/[^\-?\d.]/g, '')" @focus="$event.target.select()" @change="valChange($event, 'D', scope.$index, index)" />
            </p>
          </template>
        </el-table-column>
        <el-table-column label="流向贷方" align="right">
          <template slot-scope="scope">
            <p v-for="(item,index) in scope.row.lineList" :key="index" clss="pCell" style="height:32px;padding:0;">
              <input v-model="item.cashFlowCr" class="tx-r" :disabled="!!item.cashFlowFlag" style="padding-right:10px" oninput="value=value.replace(/[^\-?\d.]/g, '')" @focus="$event.target.select()" @change="valChange($event, 'C', scope.$index, index)" />
            </p>
          </template>
        </el-table-column>
        <el-table-column v-permiss="['38301010']" label="操作" align="center" width="100">
          <template slot-scope="{row}">
            <el-button size="mini" round type="primary" @click="saveData(row)">保存</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>10" :total="total" :page.sync="listQuery.pageIndex" :limit.sync="listQuery.pageNum" @pagination="getData" />
    </div>
  </div>
</template>
<script>
import { getFlowDatadetail, getPeriodList, getCashFlowList, updateCashFlow } from '@/api/report'
import { getNowMonth, uniqueArr, getPrevMonth, getPrevSeason } from '@/utils/index'
export default {
  name: 'FlowSubsidiary',
  filters: {
    Fixed: function(num) {
      if (!num) {
        return '0.00'
      }
      return parseFloat(num).toFixed(2)
    },
    jeSeqFormat: function(num) {
      return num < 10 ? '00' + num : num < 100 ? '0' + num : num
    }
  },
  data() {
    const userInfo = JSON.parse(sessionStorage.userInfo)
    let path = '2013'
    if (userInfo.book && (userInfo.book.coaHierarchyId == 1 || userInfo.book.coaHierarchyId == 2007)) {
      path = '2007'
    }
    return {
      tableKey: 0,
      tableData: [],
      periodList: [],
      yearArr: [],
      cashFlowList: [],
      total: 0,
      book: path,
      listLoading: true,
      listQuery: {
        pageIndex: 1,
        pageNum: 10,
        queryParam: {
          periodType: '1',
          periodYear: '',
          quarter: '',
          periodCode: getNowMonth()
        }
      }
    }
  },
  created() {
    getPeriodList().then(res => {
      this.periodList = res.data.data
      this.initYearArr()
    })
    getCashFlowList({ type: 1 }).then(res => {
      this.cashFlowList = res.data.data || []
    })
  },
  activated() {
    const param = {
      periodType: this.$route.query.type || '',
      periodYear: this.$route.query.year || '',
      quarter: this.$route.query.quarter || '',
      periodCode: this.$route.query.code || ''
    }
    this.$set(this.listQuery, 'queryParam', param)
    this.getData()
  },
  methods: {
    valChange(val, type, rIndex, cIndex) {
      console.log(type)
      const item = this.tableData[rIndex].lineList[cIndex]
      if (type === 'C') {
        this.$set(item, 'cashFlowDr', null)
      } else {
        this.$set(item, 'cashFlowCr', null)
      }
    },
    handleCompile(id) {
      const arr = this.tableData.map(it => it.id)
      this.$router.push('/voucher/detail?id=' + id + '&arr=' + arr.join(','))
    },
    getData() {
      getFlowDatadetail(this.listQuery).then(res => {
        const data = res.data.data || []
        data.forEach(row => {
          row.lineList.forEach(item => {
            item.cashFlowDr = item.cashFlowDr || null
            item.cashFlowCr = item.cashFlowCr || null
          })
        })
        this.tableData = data
        this.total = res.data.totalNum || 0
      }).catch(() => {
        this.listLoading = false
      })
    },
    typeChange(val) {
      if (val === '1') {
        this.listQuery.queryParam.periodYear = ''
        this.listQuery.queryParam.quarter = ''
        const prevMonth = getPrevMonth()
        if (this.periodList.some(it => it.id === prevMonth)) {
          this.listQuery.queryParam.periodCode = prevMonth
        } else {
          this.listQuery.queryParam.periodCode = this.periodList.length > 0 ? this.periodList[0].id : ''
        }
      } else {
        this.listQuery.queryParam.periodCode = ''
      }
      if (val === '3') {
        const prevSeason = getPrevSeason()
        const yearVal = prevSeason === '4' ? new Date().getFullYear() - 1 : new Date().getFullYear()
        if (this.yearArr.some(it => it == yearVal)) {
          this.listQuery.queryParam.periodYear = String(yearVal)
          this.listQuery.queryParam.quarter = prevSeason
        } else {
          this.listQuery.queryParam.periodYear = this.yearArr.length > 0 ? this.yearArr[0] : ''
          this.listQuery.queryParam.quarter = '1'
        }
      }
      if (val === '6') {
        const yearVal = new Date().getFullYear() - 1
        if (new Date().getMonth() < 6 && this.yearArr.some(it => it == yearVal)) {
          this.listQuery.queryParam.periodYear = String(yearVal)
        } else {
          this.listQuery.queryParam.periodYear = this.yearArr.length > 0 ? this.yearArr[0] : ''
        }
        this.listQuery.queryParam.quarter = ''
      }
      if (val === 'C') {
        const yearVal = new Date().getFullYear() - 1
        if (this.yearArr.some(it => it == yearVal)) {
          this.listQuery.queryParam.periodYear = String(yearVal)
        } else {
          this.listQuery.queryParam.periodYear = this.yearArr.length > 0 ? this.yearArr[0] : ''
        }
        this.listQuery.queryParam.quarter = ''
      }
      this.getData()
    },
    initYearArr() {
      var arr = []
      this.periodList.forEach(item => {
        arr.push(item.seasonCode.substring(0, 4))
      })
      this.yearArr = uniqueArr(arr)
    },
    saveData(row) {
      const data = row.lineList.map(item => {
        return {
          id: item.id,
          cashFlowId: item.cashFlowId,
          cashFlowCode: item.periodCode,
          accountedDr: item.accountedDr,
          accountedCr: item.accountedCr,
          cashFlowDr: item.cashFlowDr,
          cashFlowCr: item.cashFlowCr,
          periodCode: row.periodCode,
          jeHeaderId: item.jeHeaderId,
          coaCode: item.coaCode,
          cashFlowFlag: item.cashFlowFlag
        }
      })
      updateCashFlow(data).then(res => {
        if (res.data.errorCode === '0') {
          this.$message.success('明细保存完成!')
        }
      })
    }
  }
}
</script>
<style scoped>
p.pCell{
  line-height: 32px;
  margin: 0;
  padding: 0;
}
th, td {
    height: 36px;
    padding-left: 10px
}

.label {
    text-align: right;
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    padding: 0 6px 0 5px;
}
input {
  display: block;
  width: 100%;
  height: 100%;
  font-size: 12px;
  padding-right: 8px;
  border: none;
}
input[disabled] {
  background: #f9f9f9;
}
>>> .tx-r input {
  text-align: right;
}
>>> .el-table td {
  padding: 0px;
}

td span {display: block;padding-right: 10px;}
.tx-c{text-align: center!important;}
.tx-r{text-align: right!important;}
</style>
